#include "gui.h"
#include "GForm.h"

#include "platform.h"


#ifdef CLE_NAMESPACE
using namespace gui;
#endif

GForm* GForm::s_pMainForm = 0;

typedef  std::map<GHForm, GForm*>    FormMaper;
static FormMaper      s_vFormList;

GForm::GForm(GForm* paren)
:m_hForm(0)
,m_pParent(paren)
{
    if (paren != 0)
        this->setParent(m_pParent);
}

GForm::~GForm()
{
	removeForm(this);
    destroyWindow(getHandle());
    m_hForm = 0;
}

bool ShortCut::isValid() const
{
    //if ( (m_value & 0xFF00) == 0) return false;
    if ( hasCtrl() && getChar() == 0x0011) return false;
    if ( hasAlt() && getChar() == 0x0012) return false;
    if ( hasShift() && getChar() == 0x0010) return false;
    return true;
}


//static function
void   GForm::addForm( GForm* pForm)
{
	s_vFormList[pForm->getHandle()] = pForm;
}
void   GForm::removeForm( GForm* pForm)
{
	s_vFormList.erase(s_vFormList.find(pForm->getHandle()));
    dprint("FormListSize = %d\n", s_vFormList.size());
}

GForm*   GForm::getForm(GHForm handle)
{
	FormMaper::iterator itr = s_vFormList.find(handle);
	if (itr != s_vFormList.end())
		return itr->second;
	return 0;
}


long GForm::sendMessageTo(const GForm* pForm, const GMessage& msg)
{
    long ret = 0 ;

    ret = sendToForm(pForm, msg);
    return ret;
}

long GForm::callMessageFrom(GForm* pForm, const GMessage& msg)
{ 
	return messageDispatch(pForm , msg);
}

//////////////////////////////////////////////////////////////////////////

void GForm::show(int cmd /* = 1 */) const
{
    showWindow(getHandle(), cmd);
}

void GForm::close() const
{
    closeWindow(m_hForm);
}

void GForm::setFocus(bool focused /* =true */)
{
	setWindowFocus(this, focused);
}

void GForm::setCursor(GCursor::CursorShape cursor)
{
	setWindowCursor(this, cursor);
}
//////////////////////////////////////////////////////////////////////////

GRect GForm::getClientRect(GRect& rcClient) const
{
	windowClientRect(this, rcClient);
	return rcClient;
}

void GForm::resize(const GSize& size)
{
	setWindowRect(this, GRect(0,0,size.w,size.h));
}

void GForm::repaint(const GRect& rc /* = GRect */) const
{
	repaintWindow(this, rc);
}

//////////////////////////////////////////////////////////////////////////

void GForm::keysDownEvent(ShortCut& sc)
{
	ItemsMaper::iterator itr = m_shortcutMaper.find(sc.getValue());
    //dprint("keysDownEvent:ShortCut=0x%X\n", sc.getValue());
	if (itr != m_shortcutMaper.end())
		itemEvent(itr->second, 0);
}

void GForm::closeEvent()
{
    destroyWindow(getHandle());
}